// pages/seaccounts/index.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radio: '2',
    values: '',
    orderId: '121212',
    ///地址信息
    addli: '',
    arr: [],
    goodslist: [{
      goodId: '',
      goodsPrice: '',
      num: '',
      totalPrice: ''
    }, {
      goodId: '',
      goodsPrice: '',
      num: '',
      totalPrice: ''
    }],
    goodslists: [{
      goodId: '',
      goodsPrice: '',
      num: '',
      totalPrice: ''
    }, ],
    sum: 0,
    allsum:0,
    type: 0,
    payPassnu: 0,
    orderId: 0,
    showPayPwdInput: false, //是否展示密码输入层
    pwdVal: '', //输入的密码
    payFocus: true, //文本框焦点
    Loadingtime: '',
    upgradeLevel:0,//晋级要的钱
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    // let obj=JSON.parse(options.data)
    // this.setData({
    //   addli:obj
    // })
    // const eventChannel = this.getOpenerEventChannel();
	
    options.arr = decodeURIComponent(options.arr);
    console.log(JSON.parse(options.arr));
    console.log(options.sum);
    console.log(options.type);
    console.log(options.upgradeLevel);
    this.setData({
      arr: JSON.parse(options.arr),
      sum: JSON.parse(options.sum),
      type: JSON.parse(options.type),
      upgradeLevel:JSON.parse(options.upgradeLevel)
    })
    //整理数据提交
    console.log(this.data.arr);
    if (this.data.arr.length == 1) {
      this.data.goodslists[0].goodId = this.data.arr[0].id
      this.data.goodslists[0].totalPrice = this.data.arr[0].price*this.data.arr[0].num
      this.data.goodslists[0].num = this.data.arr[0].num
      this.data.goodslists[0].goodsPrice = this.data.arr[0].price*this.data.arr[0].num
      this.data.allsum=this.data.goodslists[0].goodsPrice
      // console.log(this.data.allsum);
    } else if (this.data.arr.length == 2) {
      this.data.goodslist[0].goodId = this.data.arr[0].id
      this.data.goodslist[0].totalPrice = this.data.arr[0].price*this.data.arr[0].num
      this.data.goodslist[0].num = this.data.arr[0].num
      this.data.goodslist[0].goodsPrice = this.data.arr[0].price*this.data.arr[0].num
      this.data.goodslist[1].goodId = this.data.arr[1].id
      this.data.goodslist[1].totalPrice = this.data.arr[1].price*this.data.arr[1].num
      this.data.goodslist[1].num = this.data.arr[1].num
      this.data.goodslist[1].goodsPrice = this.data.arr[1].price*this.data.arr[1].num
      console.log( this.data.goodslist[0].goodsPrice, this.data.goodslist[1].goodsPrice);
      this.data.allsum=0;
      this.data.allsum= (this.data.goodslist[0].goodsPrice+this.data.goodslist[1].goodsPrice)
      console.log(this.data.allsum);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 显示支付密码输入层
   */
  showInputLayer() {
    this.setData({
      showPayPwdInput: true,
      payFocus: true
    });
  },
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer() {
    console.log(1);
    var val = this.data.pwdVal;
    console.log(val);
    this.setData({
      showPayPwdInput: false,
      payFocus: false,
      pwdVal: val
    }, );
    if (this.data.pwdVal) {
      wx.request({
        url: app.globalData.url+'/zkxj/order/wechat/integral/pay',
        data: {
          "orderId": this.data.orderId,
          "payPass": this.data.pwdVal
        },
        method: 'POST',
        header: {
         'content-type': 'application/json',
        'token':wx.getStorageSync('token')
        },
        success: (res) => {
          console.log(res.data.code);
          if (res.data.code == 0) {
            // 定时三秒跳转对比页面
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 2000,
              mask: true
            })
            this.setData({
              Loadingtime: setInterval(function () {
                wx.redirectTo({
                  url: '/pages/orderform/index',
                })
              }, 2000)
            })

          }else if(res.data.code==500){
            wx.showToast({
              title: '支付密码错误',
              icon: 'error',
              duration: 2000,
              mask: true
            })
          }
        },

        // "fail": function (res) {
        //   wx.showToast({
        //     title: '失败',
        //     icon: 'error',
        //     duration: 1000,
        //     mask: true
        //   })
        // },
        // "complete": function (res) {
        //   wx.showToast({
        //     title: '取消',
        //     icon: 'error',
        //     duration: 1000,
        //     mask: true
        //   })
        // }

      })
    }
  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({
      payFocus: true
    });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({
      pwdVal: e.detail.value
    });

    if (e.detail.value.length >= 6) {
      this.hidePayLayer();
    }
  },
  postMoney() { // 点击确认充值
    console.log(this.data.arr);
    // wx.showLoading({
    //   title: '加载中',
    // })
    let usid = wx.getStorageSync('userId')
    console.log(this.data.addli);
    if (!this.data.addli) {
      wx.showToast({
        title: '请填写地址',
        icon: 'error',
        duration: 1000,
        mask: true
      })
    } else {
      if(this.data.radio==1){
        wx.request({
          url: app.globalData.url+'/zkxj/order/wechat/place',
          data: {
            "address": this.data.addli.address,
            "expressPrice": 0,
            // "openid":'',
            "goodList": this.data.arr.length == 1 ? this.data.goodslists : this.data.goodslist,
            "area": this.data.addli.area,
            "mobile": this.data.addli.mobile,
            "name": this.data.addli.name,
            "orderType": this.data.type,
            "payPrice": this.data.sum,
            // this.data.sum
            "payType": 1,
            "shopId": 0,
            // this.data.sum
            "upgradeLevel": this.data.upgradeLevel,
            "totalPrice": this.data.allsum,
            "userId": usid,
          },
          method: 'POST',
          header: {
           'content-type': 'application/json',
          'token':wx.getStorageSync('token')
          },
          success: (res) => {
            if (res.data.code == 0) {
              wx.requestPayment({ // 这一步是调起微信支付
                "appId": res.data.data.appId,
                "timeStamp": res.data.data.timestamp,
                "nonceStr": res.data.data.noncestr,
                "package": res.data.data.packageValue,
                "signType": "RSA",
                "paySign": res.data.data.paySign,
                "success": function (res) {
    
                  console.log(res);
                  wx.hideLoading({})
                  if(res.errMsg){
                    wx.navigateTo({
                      url: '/pages/orderform/index',
                    })
                  }
                  wx.showToast({
                    title: '成功',
                    icon: 'success',
                    duration: 1000,
                    mask: true
                  })
                },
                "fail": function (res) {
                  wx.showToast({
                    title: '失败',
                    icon: 'error',
                    duration: 1000,
                    mask: true
                  })
                },
                // "complete": function (res) {
                //   wx.showToast({
                //     title: '取消',
                //     icon: 'error',
                //     duration: 1000,
                //     mask: true
                //   })
                // }
              })
            } 
            
          },
        })
      }else{

        wx.request({
          url: app.globalData.url+'/zkxj/order/wechat/place',
          data: {
            "address": this.data.addli.address,
            "expressPrice": 0,
            // "openid":'',
            "goodList": this.data.arr.length == 1 ? this.data.goodslists : this.data.goodslist,
            "area": this.data.addli.area,
            "mobile": this.data.addli.mobile,
            "name": this.data.addli.name,
            "orderType": this.data.type,
            "payPrice": this.data.sum,
            // this.data.sum
            "payType": 2,
            "shopId": 0,
            // this.data.sum
            "upgradeLevel": this.data.upgradeLevel,
            "totalPrice": this.data.allsum,
            "userId": usid,
          },
          method: 'POST',
          header: {
           'content-type': 'application/json',
          'token':wx.getStorageSync('token')
          },
          success: (res) => {
            if (res.data.code == 0) {
              if (res.data.data.orderId) {
                //调取键盘
                this.setData({
                  showPayPwdInput: true,
                  payFocus: true,
                  orderId: res.data.data.orderId
                });
              }
            } else if (res.data.code == 500) {
              if(res.data.msg=="积分不足"){
                wx.showToast({
                  title: "积分不足",
                  icon: 'error',
                  duration: 1000,
                  mask: true
                })
              }else{
  
                wx.showToast({
                  title: "未设置支付密码",
                  icon: 'error',
                  duration: 1000,
                  mask: true
                })
                this.setData({
                  Loadingtime: setInterval(function () {
                    wx.redirectTo({
                      url: '/pages/paypass/index',
                    })
                  }, 1000)
                })
              }
            }
            // wx.requestPayment({ // 这一步是调起微信支付
            //   "appId": res.data.data.appId,
            //   "timeStamp": res.data.data.timestamp,
            //   "nonceStr": res.data.data.noncestr,
            //   "package": res.data.data.packageValue,
            //   "signType": "RSA",
            //   "paySign": res.data.data.paySign,
            //   "success": function (res) {
  
            //     console.log(res);
            //     wx.hideLoading({})
            //     if(res.errMsg){
            //       wx.navigateTo({
            //         url: '/pages/orderform/index',
            //       })
            //     }
            //     wx.showToast({
            //       title: '成功',
            //       icon: 'success',
            //       duration: 1000,
            //       mask: true
            //     })
            //   },
            //   "fail": function (res) {
            //     wx.showToast({
            //       title: '失败',
            //       icon: 'error',
            //       duration: 1000,
            //       mask: true
            //     })
            //   },
            //   // "complete": function (res) {
            //   //   wx.showToast({
            //   //     title: '取消',
            //   //     icon: 'error',
            //   //     duration: 1000,
            //   //     mask: true
            //   //   })
            //   // }
            // })
          },
        })
      }

    }


  },
  //跳转收获地址页面
  handletosaddpage() {
    wx.navigateTo({
      url: '/pages/addlist/index',
    })
  },
  onChanges(event) {
    // event.detail 为当前输入的值
    // console.log(event.detail.value);
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 关闭当前页面时取消定时器
    clearInterval(this.data.Loadingtime);
    // 页面接收值，在A页面的data里面自定义mydata接收值
    // 获取到上一页返回回来带的值
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    var data = currPage.data.data
    this.setData({
      addli: JSON.parse(data)
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 关闭当前页面时取消定时器
    clearInterval(this.data.Loadingtime);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 关闭当前页面时取消定时器
    clearInterval(this.data.Loadingtime);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})